
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author kastillo
 */
public class publicas1 {

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String algorithm = "RSA";
         boolean cifrado = false;
        KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
        generator.initialize(1024);
        KeyPair keyPair = generator.generateKeyPair();

        // Iniciar un objeto para la encr / desencrCipher
         Cipher  desCipher = Cipher.getInstance("RSA");

         BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
         String pwd = stdIn.readLine();

         byte [] cleartext = pwd.getBytes();
         String s1 = new String (cleartext);
         System.out.println ("password original:" + s1 );

         desCipher.init (Cipher.ENCRYPT_MODE, keyPair.getPublic());

         byte [ ] ciphertext = desCipher.doFinal(cleartext);
         String s2 = new String (ciphertext);
         System.out.println ("password encriptado:" + s2 );
         PrivateKey a = keyPair.getPrivate();

         // Ahora desencriptar
         desCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
         byte [] cleartext1 = desCipher.doFinal(ciphertext);
         String s3 = new String (cleartext1);
         System.out.println("password desencriptado:"+ s3 );
    }
}
